/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.gruposp2p.aularest.model.controller;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import org.gruposp2p.aularest.model.Address;
import org.gruposp2p.aularest.model.Student;
import org.gruposp2p.aularest.model.Tutor;
import org.gruposp2p.aularest.model.controller.exceptions.NonexistentEntityException;
import org.gruposp2p.aularest.model.controller.exceptions.PreexistingEntityException;

/**
 *
 * @author jj
 */
public class AddressJpaController {

    public AddressJpaController() {
        emf = Persistence.createEntityManagerFactory("AulaRest_PU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Address address) throws PreexistingEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Student studentId = address.getStudentId();
            if (studentId != null) {
                studentId = em.getReference(studentId.getClass(), studentId.getId());
                address.setStudentId(studentId);
            }
            Tutor tutorId = address.getTutorId();
            if (tutorId != null) {
                tutorId = em.getReference(tutorId.getClass(), tutorId.getId());
                address.setTutorId(tutorId);
            }
            em.persist(address);
            if (studentId != null) {
                studentId.getAddressCollection().add(address);
                studentId = em.merge(studentId);
            }
            if (tutorId != null) {
                tutorId.getAddressCollection().add(address);
                tutorId = em.merge(tutorId);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findAddress(address.getId()) != null) {
                throw new PreexistingEntityException("Address " + address + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Address address) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Address persistentAddress = em.find(Address.class, address.getId());
            Student studentIdOld = persistentAddress.getStudentId();
            Student studentIdNew = address.getStudentId();
            Tutor tutorIdOld = persistentAddress.getTutorId();
            Tutor tutorIdNew = address.getTutorId();
            if (studentIdNew != null) {
                studentIdNew = em.getReference(studentIdNew.getClass(), studentIdNew.getId());
                address.setStudentId(studentIdNew);
            }
            if (tutorIdNew != null) {
                tutorIdNew = em.getReference(tutorIdNew.getClass(), tutorIdNew.getId());
                address.setTutorId(tutorIdNew);
            }
            address = em.merge(address);
            if (studentIdOld != null && !studentIdOld.equals(studentIdNew)) {
                studentIdOld.getAddressCollection().remove(address);
                studentIdOld = em.merge(studentIdOld);
            }
            if (studentIdNew != null && !studentIdNew.equals(studentIdOld)) {
                studentIdNew.getAddressCollection().add(address);
                studentIdNew = em.merge(studentIdNew);
            }
            if (tutorIdOld != null && !tutorIdOld.equals(tutorIdNew)) {
                tutorIdOld.getAddressCollection().remove(address);
                tutorIdOld = em.merge(tutorIdOld);
            }
            if (tutorIdNew != null && !tutorIdNew.equals(tutorIdOld)) {
                tutorIdNew.getAddressCollection().add(address);
                tutorIdNew = em.merge(tutorIdNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = address.getId();
                if (findAddress(id) == null) {
                    throw new NonexistentEntityException("The address with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Address address;
            try {
                address = em.getReference(Address.class, id);
                address.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The address with id " + id + " no longer exists.", enfe);
            }
            Student studentId = address.getStudentId();
            if (studentId != null) {
                studentId.getAddressCollection().remove(address);
                studentId = em.merge(studentId);
            }
            Tutor tutorId = address.getTutorId();
            if (tutorId != null) {
                tutorId.getAddressCollection().remove(address);
                tutorId = em.merge(tutorId);
            }
            em.remove(address);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Address> findAddressEntities() {
        return findAddressEntities(true, -1, -1);
    }

    public List<Address> findAddressEntities(int maxResults, int firstResult) {
        return findAddressEntities(false, maxResults, firstResult);
    }

    private List<Address> findAddressEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Address as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Address findAddress(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Address.class, id);
        } finally {
            em.close();
        }
    }

    public int getAddressCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Address as o").getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
